require 'rubygems/package'
require 'zlib'
require 'sketchup'
require 'fileutils'

# 本代码开源地址：https://gitee.com/baisong/lijia_loader
module LiJia
module Loader 

  Your_Plugin_Name = '立家拆单'.freeze
  
  UI.menu('Plugins').add_item(Your_Plugin_Name){ check_update() }

  private

  # 查询插件版本的url
  Plugin_Version_Url = (LiJia::ChaiDan::Download_Server_Address + 'cus/plugin/version').freeze

  # 下载tar.gz压缩格式插件的url
  Plugin_Download_Url = (LiJia::ChaiDan::Download_Server_Address + 'cus/plugin/download').freeze

  # 本插件在PrivatePreferences.json里的字典名称
  Attr_Dic_Name = 'lijia_chaidan'.freeze

  # 新版插件tar.gz文件下载后，存入本地的名称，更新完毕后会被删除
  Download_Gzip_Name = "plugin.tar.gz".freeze

  # 插件文件夹下，含有插件代码，需要被载入的文件夹
  Folders_To_Load = ['ruby'].freeze

  # 要清理的旧版文件夹
  Folders_To_Overwrite = ['ruby', 'hardware', 'fittings', 'html', 'js', 'css', 'pic'].freeze

  # 1. 更新器入口方法
  def self.check_update()
    plugin_local_version = Sketchup.read_default(Attr_Dic_Name, 'version')

    Sketchup::Http::Request.new(Plugin_Version_Url).start {|request, response|
      if response.status_code == 200
        server_version = response.body
        # 对比服务器GET到的版本号与本地constant文件的VERSION，决定是直接打开，还是更新
        if(plugin_source_exist?() && plugin_local_version == server_version)
          puts "插件版本已是最新的#{server_version}，直接打开"
          load_plugin_and_open()
        else
          puts "1. 开始更新#{Your_Plugin_Name}到新版本：#{server_version}"
          clean_plugin_folders()
          download_and_overwrite(server_version) 
        end
      else
        UI.messagebox('抱歉，服务器暂时故障。')
      end
    }
  end

  # 2. 清理旧版文件：
  def self.clean_plugin_folders()
    puts "2. 清理旧版文件："
    Dir.open(build_plugin_path()) {|dir|
      dir.each{|sub|
        sub_full_path = build_plugin_path(sub)
        if File.directory? sub_full_path
          if Folders_To_Overwrite.include? sub
            FileUtils.remove_dir sub_full_path
            puts "\t文件夹：#{sub_full_path}"
          end
        else

        end
      }
    }
  end

  # 3. 下载插件新版文件，并解压缩
  def self.download_and_overwrite(server_version)
    Sketchup::Http::Request.new(Plugin_Download_Url).start {|request, response|
      if response.status_code == 200
        gz_file = File.new(build_plugin_path(Download_Gzip_Name), 'wb')
        gz_file.write response.body
        puts "3. 最新的#{server_version}版本插件下载成功，开始解压缩："
        tar_extract = Gem::Package::TarReader.new(Zlib::GzipReader.open(gz_file))
        tar_extract.rewind # The extract has to be rewinded after every iteration
        tar_extract.each { |entry| write_entry(entry) }
        tar_extract.close
        Sketchup.write_default(Attr_Dic_Name, 'version', server_version) # 把更新后的版本号写入su配置
        # File.delete gz_file #解压缩完毕后，删除掉下载的tar.gz文件

        puts "4. 载入“#{server_version}”版插件并打开……"
        load_plugin_and_open()
      end
    }
  end

  # 4. 载入新版插件并打开
  def self.load_plugin_and_open()
    original_verbose = $VERBOSE
    $VERBOSE = nil
    Folders_To_Load.each{|source_folder|
      pattern = build_plugin_path("#{source_folder}/**/*.rb")
      Dir.glob(pattern).each { |file|
        # Cannot use `Sketchup.load` because its an alias for `Sketchup.require`.
        load file
      }.size    
    }
    ensure $VERBOSE = original_verbose

    # 替换成你自己的插件入口方法
    LiJia::ChaiDanUI.auto_login_and_show_dialog() 
  end

  # 把Gem::Package::TarReader::Entry写成磁盘上的文件
  def self.write_entry(entry)
    if(entry.file?)
      full_file_dir = build_plugin_path(File.dirname(entry.full_name))
      FileUtils.makedirs full_file_dir if !File.exist? full_file_dir
      entry_file = build_plugin_path(entry.full_name)
      f=File.new(entry_file,"wb")
      f.write entry.read
      f.close()
      puts "\t#{entry.full_name}"
    elsif(entry.directory?)

    end
  end

  # 基于插件根目录，拼出插件文件的完整路径
  def self.build_plugin_path(sub_path = nil)
    if sub_path.nil?
      return File.join File.dirname(__dir__)
    else
      return File.join File.dirname(__dir__), sub_path
    end
  end

  # 判断需load的文件夹是否都在
  def self.plugin_source_exist?()
    Folders_To_Load.each{|folder|
      return false if !FileTest::exist?(build_plugin_path(folder))
    }
    return true
  end

end
end
